package com.xin.auto.lib.base.adloopvideoplayer.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.hardware.usb.UsbDevice;
import android.net.Uri;
import android.util.Log;
import android.widget.Toast;

import com.xin.auto.lib.base.FileUtils;
import com.xin.auto.lib.base.LogUtil;

import java.io.File;
import java.util.Arrays;
import java.util.Objects;

/**
 * Created by demo on 2017/4/1 0001
 */
public class UsbReceiver extends BroadcastReceiver {
    private static final String TAG = "UsbReceiver";

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (action.equals(Intent.ACTION_MEDIA_EJECT)) {
            //USB设备移除，更新UI
            LogUtil.d("USB设备移除，更新UI >>>>> ");
            Toast.makeText(context, "USB设备移除", Toast.LENGTH_SHORT).show();
            System.exit(0);
        } else if (action.equals(Intent.ACTION_MEDIA_MOUNTED)) {
            // 文件路径
            Uri uri = intent.getData();
            Log.i(TAG, "files uri:" + uri);
            if (uri != null) {
                String filePath = uri.getPath();
                Log.i(TAG, "filePath:" + filePath);
                File rootFile = new File(filePath);
                Log.i(TAG, "rootFile:" + rootFile);
                for (File file1 : Objects.requireNonNull(rootFile.listFiles())) {
                    if (file1 != null && (file1.getName().contains("medias"))) {
                        Log.d(TAG, "files :" + Arrays.toString(file1.listFiles()));
                        for (File file2 : Objects.requireNonNull(file1.listFiles())) {
                            FileUtils.mediaFileList.add(file2.getAbsolutePath());
                        }
                    }
                }
            }

            Log.i(TAG, "FileUtils.getUsbPaths: " + FileUtils.getUsbPaths(context));
        }
    }

    private UsbListener mUsbListener;
    public void setUsbListener(UsbListener usbListener) {
        this.mUsbListener = usbListener;
    }

    /**
     * USB 操作监听
     */
    public interface UsbListener {
        //USB 插入
        void insertUsb(UsbDevice device_add);

        //USB 移除
        void removeUsb(UsbDevice device_remove);

        //获取读取USB权限
        void getReadUsbPermission(UsbDevice usbDevice);

        //读取USB信息失败
        void failedReadUsb(UsbDevice usbDevice);
    }
}
